"""
告警CRUD操作
"""
from sqlalchemy.orm import Session
from app.models.alarm import Alarm
from typing import Optional, List

def get_alarm_by_id(db: Session, alarm_id: int) -> Optional[Alarm]:
    """根据ID获取告警"""
    return db.query(Alarm).filter(Alarm.id == alarm_id).first()

def get_alarms(db: Session, skip: int = 0, limit: int = 100) -> List[Alarm]:
    """获取告警列表"""
    return db.query(Alarm).offset(skip).limit(limit).all()

def get_alarms_by_level(db: Session, level: str) -> List[Alarm]:
    """根据级别获取告警列表"""
    return db.query(Alarm).filter(Alarm.level == level).all()

def get_alarms_by_status(db: Session, status: str) -> List[Alarm]:
    """根据状态获取告警列表"""
    return db.query(Alarm).filter(Alarm.status == status).all()

def create_alarm(db: Session, alarm_data: dict) -> Alarm:
    """创建告警"""
    db_alarm = Alarm(**alarm_data)
    db.add(db_alarm)
    db.commit()
    db.refresh(db_alarm)
    return db_alarm

def update_alarm(db: Session, alarm_id: int, alarm_data: dict) -> Optional[Alarm]:
    """更新告警信息"""
    db_alarm = get_alarm_by_id(db, alarm_id)
    if db_alarm:
        for key, value in alarm_data.items():
            setattr(db_alarm, key, value)
        db.commit()
        db.refresh(db_alarm)
    return db_alarm

def delete_alarm(db: Session, alarm_id: int) -> bool:
    """删除告警"""
    db_alarm = get_alarm_by_id(db, alarm_id)
    if db_alarm:
        db.delete(db_alarm)
        db.commit()
        return True
    return False